package com.petercat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PeterCatLib {
	public static String readXML(String xmlPath, String xpath) {
		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
			domFactory.setNamespaceAware(true); // never forget this!
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			Document doc = builder.parse(xmlPath);

			XPathFactory factory = XPathFactory.newInstance();
			XPath newXpath = factory.newXPath();
			XPathExpression expr = newXpath.compile(xpath);

			Object result = expr.evaluate(doc, XPathConstants.NODESET);
			NodeList nodes = (NodeList) result;
			//			for (int i = 0; i < nodes.getLength(); i++) {
			//				System.out.println(i + ":" + nodes.item(i).getNodeName());
			//				NamedNodeMap mpas = nodes.item(i).getAttributes();
			//				if (mpas != null) {
			//					for (int z = 0; z < mpas.getLength(); z++) {
			//						Node node = mpas.item(z);
			//						String name = node.getNodeName();
			//						String value = node.getNodeValue();
			//						System.out.println(name + "=" + value);
			//					}
			//				}
			//			}

			if (nodes.getLength() > 0) {
				return nodes.item(0).getNodeValue();
			}
		} catch (Exception e) {
			Logger.getLogger(PeterCatLib.class).error(e.getMessage());
			e.printStackTrace();
			return null;
		}

		return null;
	}
}
